var express = require('express');
var router = express.Router();

const common = require('../utils/common')
const JwtUtil = require('../utils/jwt');

const Client = require('../models/Client')

router.use(function (req, res, next) {
    // 我这里把登陆和注册请求去掉了，其他的多有请求都需要进行token校验
    if (req.url != '/user/login' && req.url != '/user/register') {
        let token = req.headers.token;
        let jwt = new JwtUtil(token);
        let result = jwt.verifyToken();
        // 如果考验通过就next，否则就返回登陆信息不正确
        if (result == 'err') {
            console.log(result);
            res.send({status: 403, msg: '登录已过期,请重新登录'});
            // res.render('login.html');
        } else {
            next();
        }
    } else {
        next();
    }
});

//统一返回格式
let responseData;
router.use(function (req, res, next) {
    responseData = {
        code: 0,
        msg: ""
    }
    next();
})
/** 用户注册
 *  逻辑
 *  1.用户名不能空 1.密码不能空 1.两次密码一致
 *  2.用户是否被注册(数据库查询)
 */

router.post('/user/register', function (req, res) {
    console.log(req.body);
    console.log(req.url);
    let username = req.body.username;
    let password = req.body.password;
    let repassword = req.body.repassword;
    if (!username) {
        responseData = {
            code: 1,
            msg: "用户名不能为空"
        }
        res.json(responseData);
        return false
    }
    if (!password) {
        responseData = {
            code: 1,
            msg: "密码不能为空"
        }
        res.json(responseData);
        return false
    }
    if (repassword !== repassword) {
        responseData = {
            code: 1,
            msg: "两次密码输入不一致"
        }
        res.json(responseData);
        return false
    }
    Client.findOne({
        username: username
    }).then(info => {
        if (info) {
            responseData = {
                code: 1,
                msg: "用户名已被注册"
            }
            res.json(responseData);
            return false
        } else {
            // 保存
            let user = new Client({
                username: username,
                password: password
            })
            return user.save()
        }
    }).then(newInfo => {
        responseData = {
            code: 2,
            msg: "注册成功"
        }
        res.json(responseData);
        return false
    })
})


/**
 * 用户登陆
 * 1. 判空
 * 2. 查询是否存在
 *
 * */

router.post('/user/login', (req, res) => {
    let username = req.body.username;
    let password = req.body.password;
    if (!username || !password) {
        responseData = {
            code: 1,
            msg: "用户名和密码不能为空"
        }
        res.json(responseData);
        return false
    }
    Client.findOne({
        username: username,
        password: password
    }).then(info => {
        if (info) {
            // 登陆成功，添加token验证
            let _id = info._id.toString();
            let jwt = new JwtUtil(_id);
            let token = jwt.generateToken();
            responseData = {
                code: 2,
                message: "登录成功",
                data: {
                    token: token
                }
            }
            // 发送cookies信息给浏览器
            // req.cookies.set('userInfo',JSON.stringify({
            //     _id :userInfo._id,
            //     username:userInfo.username
            // }));
            res.json(responseData)
        } else {
            responseData = {
                code: 1,
                message: "用户名或密码错误",
            }
            res.json(responseData)
            return
        }
    })
})


/**
 * 用户 操作
 * 1. 添加用户  save  create  insertMany
 * 2. 查询当前
 * 3. 更新数据
 * 4. 删除
 *
 * */

// 添加用户
router.post('/user/addUser', function (req, res) {
    let username = req.body.username;
    let password = req.body.password;
    let mailbox = req.body.mailbox;
    let phone = req.body.phone;
    if (common.isEmpty(username)) {
        responseData = {
            msg: '用户名不能为空'
        }
        res.json(responseData)
    }
    if (common.isEmpty(password)) {
        responseData = {
            msg: '密码不能为空'
        }
        res.json(responseData)
    }
    if (common.isEmpty(mailbox)) {
        responseData = {
            msg: '邮箱不能为空'
        }
        res.json(responseData)
    }
    if (common.isEmpty(phone)) {
        responseData = {
            msg: '手机号不能为空'
        }
        res.json(responseData)
    }
    Client.create({
        username: username,
        password: username,
        mailbox: mailbox,
        phone: phone
    }).then(doc => {
        if (doc) {
            console.log('res', doc);
            responseData = {
                code: 1,
                data: doc,
                msg: '用户添加成功'
            }
            console.log('responseData', responseData);
            res.json(responseData)
        } else {
            responseData = {
                code: 2,
                msg: '用户添加失败'
            }
            res.json(responseData)
        }
    }).catch(err => {
        responseData = {
            code: 2,
            msg: '用户添加失败'
        }
        res.json(responseData)
    })
})


// 查询当前用户
router.get('/user/edit', function (req, res) {
    let id = req.query.id
    console.log(req.query)
    if (common.isEmpty(id)) {
        responseData = {
            msg: '查询失败'
        }
        res.json(responseData)
    }
    Client.findById({
        _id: id
    }).then(doc => {
        if (res) {
            responseData = {
                msg: '查询成功',
                data: doc
            }
            res.json(responseData)
        } else {
            responseData = {
                msg: '查询失败',
                data: []
            }
            res.json(responseData)
        }
    }).catch(err => {
        responseData = {
            msg: '查询失败',
            data: []
        }
        res.json(responseData)
    })
})

// 用户更新
router.post('/user/update', function (req, res) {
    let mailbox = req.body.mailbox;
    let phone = req.body.phone;
    let id = req.body.id;
    Client.updateOne({
        _id: id,
    }, {
        mailbox: mailbox,
        phone: phone
    }).then(doc => {
        if (doc) {
            responseData = {
                code:1,
                msg: '更新成功'
            }
            res.json(responseData)
        } else {
            responseData = {
                code:0,
                msg: '更新失败'
            }
            res.json(responseData)
        }
    })
})

// 删除
// 用户删除
router.delete('/user/del', function (req, res) {
    let id = req.body.id;
    Client.findByIdAndRemove({
        _id: id
    }).then(doc=> {
        if (doc) {
            responseData = {
                code:1,
                msg: '删除成功'
            }
            res.json(responseData)
        } else {
            responseData = {
                code:0,
                msg: '删除失败'
            }
            res.json(responseData)
        }
    })
})
module.exports = router;
